<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>C++日新月异的未来代码：C++11（上） | 澪贰</title><meta name="author" content="澪贰"><meta name="copyright" content="澪贰"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="C++11能更好地用于系统开发和库开发、语法更加泛华和简单化、更加稳定和安全，不仅功能更强大，而且能提升程序员的开发效率，公司实际项目开发中也用得比较多，所以我们要作为一个重点去学习">
<meta property="og:type" content="article">
<meta property="og:title" content="C++日新月异的未来代码：C++11（上）">
<meta property="og:url" content="http://example.com/2025/05/28/CPP%E8%BF%9B%E9%98%B6/C++11%EF%BC%88%E4%B8%8A%EF%BC%89/index.html">
<meta property="og:site_name" content="澪贰">
<meta property="og:description" content="C++11能更好地用于系统开发和库开发、语法更加泛华和简单化、更加稳定和安全，不仅功能更强大，而且能提升程序员的开发效率，公司实际项目开发中也用得比较多，所以我们要作为一个重点去学习">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250526131149.png">
<meta property="article:published_time" content="2025-05-28T01:20:58.000Z">
<meta property="article:modified_time" content="2025-05-28T01:20:58.000Z">
<meta property="article:author" content="澪贰">
<meta property="article:tag" content="C++">
<meta property="article:tag" content="C++11">
<meta property="article:tag" content="lambda">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250526131149.png"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "C++日新月异的未来代码：C++11（上）",
  "url": "http://example.com/2025/05/28/CPP%E8%BF%9B%E9%98%B6/C++11%EF%BC%88%E4%B8%8A%EF%BC%89/",
  "image": "https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250526131149.png",
  "datePublished": "2025-05-28T01:20:58.000Z",
  "dateModified": "2025-05-28T01:20:58.000Z",
  "author": [
    {
      "@type": "Person",
      "name": "澪贰",
      "url": "http://example.com/"
    }
  ]
}</script><link rel="shortcut icon" href="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/cat_icon.ico"><link rel="canonical" href="http://example.com/2025/05/28/CPP%E8%BF%9B%E9%98%B6/C++11%EF%BC%88%E4%B8%8A%EF%BC%89/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!true && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          const hour = new Date().getHours()
          const isNight = hour <= 6 || hour >= 18
          if (theme === undefined) isNight ? activateDarkMode() : activateLightMode()
          else theme === 'light' ? activateLightMode() : activateDarkMode()
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"未找到符合您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":230,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":150,"languages":{"author":"作者: 澪贰","link":"链接: ","source":"来源: 澪贰","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'medium_zoom',
  Snackbar: {"chs_to_cht":"已切换为繁体中文","cht_to_chs":"已切换为简体中文","day_to_night":"已切换为深色模式","night_to_day":"已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"top-right"},
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'C++日新月异的未来代码：C++11（上）',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/css/custom.css" media="defer" onload="this.media='all'"><script src="https://npm.elemecdn.com/echarts@4.9.0/dist/echarts.min.js"></script><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-double-row-display@1.00/cardlistpost.min.css"/>
<style>#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags:before {content:"\A";
  white-space: pre;}#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags > .article-meta__separator{display:none}</style>
<link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-categories-card@1.0.0/lib/categorybar.css"><link rel="stylesheet" href="https://unpkg.zhimg.com/hexo-butterfly-footer-beautify@1.0.0/lib/runtime.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiperstyle.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/animate.min.css" media="print" onload="this.media='screen'"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 7.3.0"></head><body><div id="web_bg" style="background-image: url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/water02.jpg);"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/zero_two.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">96</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">74</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">9</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home-lg"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><span class="site-page group hide"><i class="fa-fw fas fa-list"></i><span> 列表</span><i class="fas fa-chevron-down"></i></span><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-envelope-open"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250526131149.png);"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">澪贰</span></a><a class="nav-page-title" href="/"><span class="site-name">C++日新月异的未来代码：C++11（上）</span></a></span><div id="menus"><div id="search-button"><span class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></span></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home-lg"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><span class="site-page group hide"><i class="fa-fw fas fa-list"></i><span> 列表</span><i class="fas fa-chevron-down"></i></span><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-envelope-open"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">C++日新月异的未来代码：C++11（上）</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2025-05-28T01:20:58.000Z" title="发表于 2025-05-28 09:20:58">2025-05-28</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-05-28T01:20:58.000Z" title="更新于 2025-05-28 09:20:58">2025-05-28</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/C-%E8%BF%9B%E9%98%B6/">C++进阶</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">总字数:</span><span class="word-count">3880</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>13分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><div id="post-outdate-notice" data="{&quot;limitDay&quot;:365,&quot;messagePrev&quot;:&quot;It has been&quot;,&quot;messageNext&quot;:&quot;days since the last update, the content of the article may be outdated.&quot;,&quot;postUpdate&quot;:&quot;2025-05-28 09:20:58&quot;}" hidden></div><p><a target="_blank" rel="noopener" href="https://en.cppreference.com/w/cpp/11">C++11</a> 能更好地用于系统开发和库开发、语法更加泛华和简单化、更加稳定和安全，不仅功能更强大，而且能提升程序员的开发效率，公司实际项目开发中也用得比较多，所以我们要作为一个重点去学习</p>
<h1 id="统一的列表初始化"><a href="#统一的列表初始化" class="headerlink" title="统一的列表初始化"></a>统一的列表初始化</h1><h2 id="普通-初始化"><a href="#普通-初始化" class="headerlink" title="普通{ }初始化"></a>普通{ }初始化</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">struct</span> <span class="title class_">Point</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> _x;</span><br><span class="line">	<span class="type">int</span> _y;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="type">int</span> array1[] = &#123; <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span> &#125;;</span><br><span class="line">	<span class="type">int</span> array2[<span class="number">5</span>] = &#123; <span class="number">0</span> &#125;;</span><br><span class="line">	Point p = &#123; <span class="number">1</span>, <span class="number">2</span> &#125;;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在 <code>C++98</code> 中，标准允许使用花括号{}对数组或者结构体元素进行统一的列表初始值设定</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">struct</span> <span class="title class_">Point</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> _x;</span><br><span class="line">	<span class="type">int</span> _y;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="type">int</span> x1 = <span class="number">1</span>;</span><br><span class="line">	<span class="type">int</span> x2&#123; <span class="number">2</span> &#125;;</span><br><span class="line">	<span class="type">int</span> array1[]&#123; <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span> &#125;;</span><br><span class="line">	<span class="type">int</span> array2[<span class="number">5</span>]&#123; <span class="number">0</span> &#125;;</span><br><span class="line">	Point p&#123; <span class="number">1</span>, <span class="number">2</span> &#125;;</span><br><span class="line">	<span class="comment">// C++11中列表初始化也可以适用于new表达式中</span></span><br><span class="line">	<span class="type">int</span>* pa = <span class="keyword">new</span> <span class="type">int</span>[<span class="number">4</span>] &#123; <span class="number">0</span> &#125;;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>C++11</code> 扩大了用大括号括起的列表(初始化列表)的使用范围，使其可用于所有的内置类型和用户自定义的类型，使用初始化列表时，可添加等号 <code>=</code>，也可不添加</p>
<p>简单来说，<code>C++11</code> 一切皆可用 <code>&#123;&#125;</code> 初始化，并且可以不写 <code>=</code>，建议日常定义，不要去掉 <code>=</code>，但是我们要能看懂</p>
<p>🔥<strong>值得注意的是：</strong> 像 <code>Point p1 = &#123; 1, 1 &#125;</code> ，是一种多参数隐式转化，无论哪一种初始化方式都是要调用对应的构造函数的</p>
<h2 id="initializer-list"><a href="#initializer-list" class="headerlink" title="initializer_list"></a>initializer_list</h2><p><a target="_blank" rel="noopener" href="https://legacy.cplusplus.com/reference/initializer_list/initializer_list/?kw=initializer_list">initializer_list</a> 是 <code>C++11</code> 引入的一个轻量级容器，用于支持统一的初始化语法和参数列表初始化。它允许函数或类接收任意数量的同类型参数，并提供简洁的初始化方式</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">vector&lt;<span class="type">int</span>&gt; v1 = &#123; <span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span> &#125;; <span class="comment">// 调用 vector 的 initializer_list 构造函数</span></span><br></pre></td></tr></table></figure>

<p><code>stl</code> 中的容器基本都是支持 <code>initializer_list</code> 初始化的，这初始化的方式和上面的隐式类型不同，具体方式如下：</p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/f7f5fada9a8d452384e4bddb14d52d65.png" alt="在这里插入图片描述"></p>
<p>首先要知道 <code>initializer_list</code> 主要有这三个成员</p>
<ol>
<li>创建一个临时数组（存储在栈上），包含元素 <code>&#123;1, 2, 3&#125;</code></li>
<li>生成一个 <code>initializer_list&lt;int&gt;</code> 对象，该对象引用临时数组（内部保存数组的起始地址和长度）</li>
<li><code>initializer_list</code> 引用临时数组（不拥有其内存），<code>vector</code> 会将临时数组的内容复制元素到自己的内存空间（堆上），与临时数组无关</li>
<li>临时数组被销毁</li>
</ol>
<p>🔥<strong>值得注意的是：</strong> <code>vector</code> 是复制引用数组的元素，而不是直接接收，是因为该临时数组销毁之后，如果 <code>vector</code> 还接收着的话会造成悬空引用</p>
<p>因此 <code>initializer_list</code> 的存在还是很有必要的：</p>
<p>在 <code>C++11</code> 之前，若想让函数接收一个类似 <code>&#123;1, 2, 3&#125;</code> 的初始化列表作为参数，需要通过数组或容器（如 <code>vector</code>）传递，不够直观。<code>initializer_list</code> 允许函数直接以初始化列表为参数，使代码更符合直觉</p>
<h1 id="声明"><a href="#声明" class="headerlink" title="声明"></a>声明</h1><h2 id="auto、nullptr"><a href="#auto、nullptr" class="headerlink" title="auto、nullptr"></a>auto、nullptr</h2><p>该 <code>C++</code> 增加的特性在前面的文章进行过详细讲解，不过多叙述</p>
<blockquote>
<p>传送门：<a target="_blank" rel="noopener" href="https://blog.csdn.net/Zero_VPN/article/details/144131104">C++命运石之门代码抉择：C++入门（下）</a></p>
</blockquote>
<h2 id="decltype"><a href="#decltype" class="headerlink" title="decltype"></a>decltype</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// decltype的一些使用使用场景</span></span><br><span class="line"><span class="function"><span class="keyword">template</span>&lt;<span class="keyword">class</span> T1, <span class="keyword">class</span> T2&gt;</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">F</span><span class="params">(T1 t1, T2 t2)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="keyword">decltype</span>(t1 * t2) ret;</span><br><span class="line">	cout &lt;&lt; <span class="built_in">typeid</span>(ret).<span class="built_in">name</span>() &lt;&lt; endl;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="type">const</span> <span class="type">int</span> x = <span class="number">1</span>;</span><br><span class="line">	<span class="type">double</span> y = <span class="number">2.2</span>;</span><br><span class="line">	<span class="keyword">decltype</span>(x * y) ret; <span class="comment">// ret的类型是double</span></span><br><span class="line">	<span class="keyword">decltype</span>(&amp;x) p;      <span class="comment">// p的类型是int*</span></span><br><span class="line">	cout &lt;&lt; <span class="built_in">typeid</span>(ret).<span class="built_in">name</span>() &lt;&lt; endl;</span><br><span class="line">	cout &lt;&lt; <span class="built_in">typeid</span>(p).<span class="built_in">name</span>() &lt;&lt; endl;</span><br><span class="line">	<span class="built_in">F</span>(<span class="number">1</span>, <span class="string">&#x27;a&#x27;</span>);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>typeid().name()</code> 是一种读取类型的方式，但是无法使用，<code>decltype</code> 和 <code>auto</code> 类似，可以自动推导类型，<code>auto</code> 只能推导，<code>decltype</code> 可以推导并使用</p>
<h1 id="左值右值"><a href="#左值右值" class="headerlink" title="左值右值"></a>左值右值</h1><h2 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h2><p>传统的 <code>C++</code> 语法中就有引用的语法，而 <code>C++11</code> 中新增了的右值引用语法特性，所以从现在开始我们之前学习的引用就叫做左值引用。无论左值引用还是右值引用，都是给对象取别名</p>
<p>🚩<strong>什么是左值？什么是左值引用？</strong></p>
<blockquote>
<p>左值是一个表示数据的表达式(如变量名或解引用的指针)，我们可以获取它的地址，一般可以对它赋值，左值可以出现赋值符号的左边，右值不能出现在赋值符号左边。定义时 <code>const</code> 修饰符后的左值，不能给他赋值，但是可以取它的地址。左值引用就是给左值的引用，给左值取别名</p>
</blockquote>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="comment">// 以下的p、b、c、*p都是左值，字符串也算一种左值</span></span><br><span class="line">	<span class="type">int</span>* p = <span class="keyword">new</span> <span class="built_in">int</span>(<span class="number">0</span>);</span><br><span class="line">	<span class="type">int</span> b = <span class="number">1</span>;</span><br><span class="line">	<span class="type">const</span> <span class="type">int</span> c = <span class="number">2</span>;</span><br><span class="line">	<span class="comment">// 以下几个是对上面左值的左值引用</span></span><br><span class="line">	<span class="type">int</span>*&amp; rp = p;</span><br><span class="line">	<span class="type">int</span>&amp; rb = b;</span><br><span class="line">	<span class="type">const</span> <span class="type">int</span>&amp; rc = c;</span><br><span class="line">	<span class="type">int</span>&amp; pvalue = *p;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>简单来说就是能够<code>取地址</code>的就是<code>左值</code>，左值大多数能赋值（除 <code>const</code> 左值），为左值取别名的变量就是 <code>左值引用</code></p>
<p>🚩<strong>什么是右值？什么是右值引用？</strong></p>
<blockquote>
<p>右值也是一个表示数据的表达式，如：字面常量、表达式返回值，函数返回值(这个不能是左值引用返回)等等，右值可以出现在赋值符号的右边，但是不能出现出现在赋值符号的左边，右值不能取地址。右值引用就是对右值的引用，给右值取别名</p>
</blockquote>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="type">double</span> x = <span class="number">1.1</span>, y = <span class="number">2.2</span>;</span><br><span class="line">	<span class="comment">// 以下几个都是常见的右值</span></span><br><span class="line">	<span class="number">10</span>;</span><br><span class="line">	x + y;</span><br><span class="line">	<span class="built_in">fmin</span>(x, y);</span><br><span class="line">	<span class="comment">// 以下几个都是对右值的右值引用</span></span><br><span class="line">	<span class="type">int</span>&amp;&amp; rr1 = <span class="number">10</span>;</span><br><span class="line">	<span class="type">double</span>&amp;&amp; rr2 = x + y;</span><br><span class="line">	<span class="type">double</span>&amp;&amp; rr3 = <span class="built_in">fmin</span>(x, y);</span><br><span class="line">	<span class="comment">// 这里编译会报错：error C2106: “=”: 左操作数必须为左值</span></span><br><span class="line">	<span class="number">10</span> = <span class="number">1</span>;</span><br><span class="line">	x + y = <span class="number">1</span>;</span><br><span class="line">	<span class="built_in">fmin</span>(x, y) = <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>简单来说，不能取地址的，就是右值，右值不能做左操作数，为右值取别名的变量就是 <code>右值引用</code></p>
<p>🔥<strong>值得注意的是：</strong> 右值引用之后，是可以对引用变量取地址修改的，不想修改的话加 <code>const</code> 即可</p>
<h2 id="左值引用与右值引用比较"><a href="#左值引用与右值引用比较" class="headerlink" title="左值引用与右值引用比较"></a>左值引用与右值引用比较</h2><p>🚩<strong>左值引用</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="comment">// 左值引用只能引用左值，不能引用右值。</span></span><br><span class="line">	<span class="type">int</span> a = <span class="number">10</span>;</span><br><span class="line">	<span class="type">int</span>&amp; ra1 = a;   <span class="comment">// ra为a的别名</span></span><br><span class="line">	<span class="comment">//int&amp; ra2 = 10;   // 编译失败，因为10是右值</span></span><br><span class="line">	<span class="comment">// const左值引用既可引用左值，也可引用右值。</span></span><br><span class="line">	<span class="type">const</span> <span class="type">int</span>&amp; ra3 = <span class="number">10</span>;</span><br><span class="line">	<span class="type">const</span> <span class="type">int</span>&amp; ra4 = a;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol>
<li>左值引用只能引用左值，不能引用右值</li>
<li>但是 <code>const</code> 左值引用既可引用左值，也可引用右值</li>
</ol>
<p>因为两者的生命周期不同，会造成悬空。假设允许 <code>int&amp; ra2 = 10</code>，<code>10</code> 是右值，无固定内存地址，生命周期短暂。若 <code>ra2</code> 绑定到 <code>10</code>，当表达式结束后，<code>10</code> 被销毁，<code>ra2</code> 将悬空。而 <code>const int&amp;</code> 通过延长右值生命周期，创建一个临时对象存储右值，并将引用绑定到该临时对象，避免了此问题</p>
<p>🚩<strong>右值引用</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="comment">// 右值引用只能右值，不能引用左值。</span></span><br><span class="line">	<span class="type">int</span>&amp;&amp; r1 = <span class="number">10</span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// error C2440: “初始化”: 无法从“int”转换为“int &amp;&amp;”</span></span><br><span class="line">	<span class="comment">// message : 无法将左值绑定到右值引用</span></span><br><span class="line">	<span class="type">int</span> a = <span class="number">10</span>;</span><br><span class="line">	<span class="type">int</span>&amp;&amp; r2 = a;</span><br><span class="line">	<span class="comment">// 右值引用可以引用move以后的左值</span></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol>
<li>右值引用只能右值，不能引用左值</li>
<li>但是右值引用可以 <code>move</code> 以后的左值</li>
</ol>
<p>右值引用是个临时存储的对象，如果引用左值的话，原本左值中正在使用的值会因为右值引用的销毁而受影响，但是可以使用 <code>move</code> 转成右值，下面会对 <code>move</code> 进行解析</p>
<h2 id="左值引用与右值引用的应用"><a href="#左值引用与右值引用的应用" class="headerlink" title="左值引用与右值引用的应用"></a>左值引用与右值引用的应用</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">string&amp; <span class="title">func</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="type">static</span> string a;</span><br><span class="line">	<span class="keyword">return</span> a;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	string ret = <span class="built_in">func</span>();</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>之前我们学习过引用返回，是一种左值引用，将变量的地址返回回去，但是这种方式的局限性巨大，大部分情况下返回的是一个局部变量，那么就不能用左值引用返回了，这里只能使用传值返回，传值返回会导致至少 <code>1</code> 次拷贝构造(如果是一些旧一点的编译器可能是两次拷贝构造)</p>
<p><strong>那么右值引用和移动语义解决上述问题：</strong></p>
<p>首先介绍一个概念</p>
<ul>
<li><strong>普通类型的右值：</strong> 纯右值</li>
<li><strong>自定义类型的右值：</strong> 将亡值</li>
</ul>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/ada0bf6f9c474b14b7fe17dfe245b699.png" alt="在这里插入图片描述"></p>
<p>早期编译器还没有优化的时候返回的 <code>str</code> 先传递给临时变量，这个过程是拷贝构造，是一次深拷贝，由于此时的临时变量是右值，所以可以使用移动构造，下面将详细介绍移动构造的实现：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 拷贝构造</span></span><br><span class="line">		<span class="built_in">string</span>(<span class="type">const</span> string&amp; s)</span><br><span class="line">			:_str(<span class="literal">nullptr</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			cout &lt;&lt; <span class="string">&quot;string(const string&amp; s) -- 深拷贝&quot;</span> &lt;&lt; endl;</span><br><span class="line">			<span class="function">string <span class="title">tmp</span><span class="params">(s._str)</span></span>;</span><br><span class="line">			<span class="built_in">swap</span>(tmp);</span><br><span class="line">		&#125;</span><br><span class="line"><span class="comment">//移动构造</span></span><br><span class="line">		<span class="built_in">string</span>(string&amp;&amp; s)</span><br><span class="line">			:_str(<span class="literal">nullptr</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			cout &lt;&lt; <span class="string">&quot;string(string&amp;&amp; s) -- 移动拷贝&quot;</span> &lt;&lt; endl;</span><br><span class="line">			<span class="comment">//......</span></span><br><span class="line">		&#125;</span><br></pre></td></tr></table></figure>

<p>如图为移动构造的大概框架</p>
<ol>
<li><p><strong>参数传递：</strong> 移动构造函数接收一个右值引用参数 <code>string&amp;&amp; s</code></p>
</li>
<li><p><strong>资源转移：</strong> 举个例子，省略号处可能执行 <code>data = s.data</code> 和 <code>size = s.size</code> 的操作，看起来好像是转移了资源，其实不是的，只是把原来对象的指针和属性转移给了新对象，并没有拷贝原来对象的主要数据，简单来说就是资源所有权的转移</p>
</li>
<li><p><strong>原对象资源清理：</strong> 将原对象的data指针置为 <code>nullptr</code>，<code>size</code> 置为 <code>0</code>，这样当原对象在析构时（即出了局部作用域时），由于资源所有权被转移给新对象，所以这部分资源不会给释放</p>
</li>
</ol>
<p>通过这样的方式，移动构造函数实现了资源的高效转移，避免了像拷贝构造函数那样对资源进行复制，提高了对象创建和资源管理的效率</p>
<hr>
<p>通过不断的编译器优化，如今已经可以只使用一次移动构造就能解决了</p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/a621ddd5e0ad421488bc41f5f61755f5.png" alt="在这里插入图片描述"></p>
<p>两个步骤直接合二为一，编译器通过特殊处理，将本来是左值的 <code>str</code> 返回值，识别成将亡值，直接使用移动构造转移资源</p>
<p><strong>不仅仅有移动构造，还有移动赋值：</strong></p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/186c3f5b799f48d281c81d7bf779f3fb.png" alt="在这里插入图片描述"></p>
<p><strong>移动构造：</strong> <code>func</code> 函数中创建了 <code>string</code> 对象 <code>str</code> ，当 <code>return str</code> 时，会调用移动构造函数。因为 <code>str</code> 是函数内局部对象，返回时将其资源以移动方式构造一个临时对象用于返回值。这避免了对字符串内容的深拷贝，直接转移资源所有权，提升效率 </p>
<p><strong>移动赋值：</strong> 在 <code>main</code> 函数中，先创建了 <code>string</code> 对象 <code>ret2</code> ，然后 <code>ret2 = func();</code> ，这里<code>func()</code> 返回一个临时对象，此操作会调用 <code>string</code> 类的移动赋值运算符。它将 <code>func</code> 函数返回的临时对象的资源（如内部存储字符串的指针等相关资源）转移给 <code>ret2</code> ，而不是进行字符串内容的复制，同样是为了提高效率</p>
<p>🔥<strong>值得注意的是：</strong> 移动构造函数是用于创建一个新对象，并从另一个对象（通常是临时对象）那里获取资源所有权；而移动赋值是用于将一个已存在对象的资源所有权转移给另一个已存在的对象。简单来说，移动构造函数是在对象创建时起作用，而移动赋值是在对象已经存在之后进行资源转移时起作用</p>
<hr>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="function">string <span class="title">s1</span><span class="params">(<span class="string">&quot;hello world&quot;</span>)</span></span>;</span><br><span class="line">	<span class="function">string <span class="title">s2</span><span class="params">(s1)</span></span>;</span><br><span class="line">	<span class="function">string <span class="title">s3</span><span class="params">(move(s1))</span></span>;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>了解了右值引用相关的移动构造，那么 <code>move</code> 就好解释多了，<code>move</code> 简单理解就是把资源完全复制到一个右值新对象，对原来的对象并没有修改</p>
<p><code>s2</code> 这里 <code>s1</code> 是左值，调用的是拷贝构造，这里我们把 <code>s1</code> <code>move</code>处理以后，会被当成右值，调用移动构造，但是这里要注意，一般是不要这样用的，因为我们会发现 <code>s1</code> 的资源被转移给了 <code>s3</code>，<code>s1</code> 被置空了</p>
<h2 id="完美转发"><a href="#完美转发" class="headerlink" title="完美转发"></a>完美转发</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">Fun</span><span class="params">(<span class="type">int</span>&amp; x)</span> </span>&#123; cout &lt;&lt; <span class="string">&quot;左值引用&quot;</span> &lt;&lt; endl; &#125;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">Fun</span><span class="params">(<span class="type">const</span> <span class="type">int</span>&amp; x)</span> </span>&#123; cout &lt;&lt; <span class="string">&quot;const 左值引用&quot;</span> &lt;&lt; endl; &#125;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">Fun</span><span class="params">(<span class="type">int</span>&amp;&amp; x)</span> </span>&#123; cout &lt;&lt; <span class="string">&quot;右值引用&quot;</span> &lt;&lt; endl; &#125;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">Fun</span><span class="params">(<span class="type">const</span> <span class="type">int</span>&amp;&amp; x)</span> </span>&#123; cout &lt;&lt; <span class="string">&quot;const 右值引用&quot;</span> &lt;&lt; endl; &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> T&gt;</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">PerfectForward</span><span class="params">(T&amp;&amp; t)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="built_in">Fun</span>(t);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="built_in">PerfectForward</span>(<span class="number">10</span>);           <span class="comment">// 右值</span></span><br><span class="line">	<span class="type">int</span> a;</span><br><span class="line">	<span class="built_in">PerfectForward</span>(a);            <span class="comment">// 左值</span></span><br><span class="line">	<span class="built_in">PerfectForward</span>(std::<span class="built_in">move</span>(a)); <span class="comment">// 右值</span></span><br><span class="line">	<span class="type">const</span> <span class="type">int</span> b = <span class="number">8</span>;</span><br><span class="line">	<span class="built_in">PerfectForward</span>(b);      <span class="comment">// const 左值</span></span><br><span class="line">	<span class="built_in">PerfectForward</span>(std::<span class="built_in">move</span>(b)); <span class="comment">// const 右值</span></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>模板中的 <code>&amp;&amp;</code> 不代表右值引用，而是万能引用，其既能接收左值又能接收右值，模板的万能引用只是提供了能够接收同时接收左值引用和右值引用的能力</p>
<p><strong>T&amp;&amp; 的推导规则：</strong></p>
<ul>
<li><p>当传入左值（如变量 <code>a</code>）时，<code>T</code> 被推导为左值引用类型（如 <code>int&amp;</code>），此时 <code>T&amp;&amp;</code> 折叠为 <code>int&amp;</code>（即左值引用），也叫引用折叠</p>
</li>
<li><p>当传入右值（如 <code>10</code> 或 <code>move(a)</code>）时，<code>T</code> 被推导为非引用类型（如 <code>int</code>），此时 <code>T&amp;&amp;</code> 成为 <code>int&amp;&amp;</code>（即右值引用）</p>
</li>
</ul>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/354dbc05782b45f186af3da8f299f538.png" alt="在这里插入图片描述"></p>
<p>但运行之后发现全都是左值，并没有按照传入实参的类型调用</p>
<p><strong>关键点：</strong> 变量名本身永远是左值，无论这个变量是左值引用还是右值引用类型</p>
<p><strong>为什么 t 是左值？</strong></p>
<blockquote>
<p><code>T&amp;&amp;</code> 无论被推导成什么，都是根据 <code>t</code> 这个实参的传入进行调整的，我们知道右值是不可以被修改的，所以这里理应是个左值，而且 <code>C++</code> 标准明确规定：变量名（无论其类型是左值引用还是右值引用）都是左值表达式</p>
</blockquote>
<p>因此，<code>Fun(t)</code> 中的 <code>t</code> 始终被视为左值，调用 <code>Fun(int&amp;)</code> 或 <code>Fun(const int&amp;)</code></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">Fun</span><span class="params">(<span class="type">int</span>&amp; x)</span> </span>&#123; cout &lt;&lt; <span class="string">&quot;左值引用&quot;</span> &lt;&lt; endl; &#125;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">Fun</span><span class="params">(<span class="type">const</span> <span class="type">int</span>&amp; x)</span> </span>&#123; cout &lt;&lt; <span class="string">&quot;const 左值引用&quot;</span> &lt;&lt; endl; &#125;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">Fun</span><span class="params">(<span class="type">int</span>&amp;&amp; x)</span> </span>&#123; cout &lt;&lt; <span class="string">&quot;右值引用&quot;</span> &lt;&lt; endl; &#125;</span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">Fun</span><span class="params">(<span class="type">const</span> <span class="type">int</span>&amp;&amp; x)</span> </span>&#123; cout &lt;&lt; <span class="string">&quot;const 右值引用&quot;</span> &lt;&lt; endl; &#125;</span><br><span class="line"><span class="comment">// std::forward&lt;T&gt;(t)在传参的过程中保持了t的原生类型属性。</span></span><br><span class="line"><span class="function"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> T&gt;</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">PerfectForward</span><span class="params">(T&amp;&amp; t)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="built_in">Fun</span>(forward&lt;T&gt;(t));</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="built_in">PerfectForward</span>(<span class="number">10</span>);           <span class="comment">// 右值</span></span><br><span class="line">	<span class="type">int</span> a;</span><br><span class="line">	<span class="built_in">PerfectForward</span>(a);            <span class="comment">// 左值</span></span><br><span class="line">	<span class="built_in">PerfectForward</span>(std::<span class="built_in">move</span>(a)); <span class="comment">// 右值</span></span><br><span class="line">	<span class="type">const</span> <span class="type">int</span> b = <span class="number">8</span>;</span><br><span class="line">	<span class="built_in">PerfectForward</span>(b);      <span class="comment">// const 左值</span></span><br><span class="line">![请添加图片描述](https:<span class="comment">//i-blog.csdnimg.cn/direct/5331a7028bb842c8987b625c5cc4c15e.png)</span></span><br><span class="line">	<span class="built_in">PerfectForward</span>(std::<span class="built_in">move</span>(b)); <span class="comment">// const 右值</span></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>因此保持参数的原始值类别（左值或右值）就要用到 <code>forward</code></p>
<ul>
<li>如果原始参数是左值，<code>T</code> 会被推导为左值引用（如 <code>int&amp;</code>），<code>forward&lt;int&amp;&gt;(t)</code> 返回左值引用</li>
<li>如果原始参数是右值，<code>T</code> 会被推导为非引用类型（如 <code>int</code>），<code>forward&lt;int&gt;(t)</code> 返回右值引用（<code>int&amp;&amp;</code>）</li>
</ul>
<p>这样，<code>t</code> 的原始值类别（左值 &#x2F; 右值）就被正确传递给 <code>Fun</code> 函数</p>
<hr>
<h1 id="希望读者们多多三连支持"><a href="#希望读者们多多三连支持" class="headerlink" title="希望读者们多多三连支持"></a>希望读者们多多三连支持</h1><h1 id="小编会继续更新"><a href="#小编会继续更新" class="headerlink" title="小编会继续更新"></a>小编会继续更新</h1><h1 id="你们的鼓励就是我前进的动力！"><a href="#你们的鼓励就是我前进的动力！" class="headerlink" title="你们的鼓励就是我前进的动力！"></a>你们的鼓励就是我前进的动力！</h1><p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/8e96cf65884a4c7bbccb35cc1dcf3f94.png" alt="请添加图片描述"></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="http://example.com">澪贰</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2025/05/28/CPP%E8%BF%9B%E9%98%B6/C++11%EF%BC%88%E4%B8%8A%EF%BC%89/">http://example.com/2025/05/28/CPP进阶/C++11（上）/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="http://example.com" target="_blank">澪贰</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/C/">C++</a><a class="post-meta__tags" href="/tags/C-11/">C++11</a><a class="post-meta__tags" href="/tags/lambda/">lambda</a></div><div class="post-share"><div class="social-share" data-image="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250526131149.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i>赞助</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/Wechat.png" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/Wechat.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/Alipay.png" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/Alipay.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><a class="pagination-related" href="/2025/06/02/CPP%E8%BF%9B%E9%98%B6/C++11%EF%BC%88%E4%B8%8B%EF%BC%89/" title="C++日新月异的未来代码：C++11（下）"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250527175202.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="info"><div class="info-1"><div class="info-item-1">上一篇</div><div class="info-item-2">C++日新月异的未来代码：C++11（下）</div></div><div class="info-2"><div class="info-item-1">接上篇，继续学习C++11的常用新特性 lambda表达式引入lambda 表达式是一种匿名函数对象，允许在代码中直接定义和使用小型的函数，无需额外定义函数或函数对象类，这么讲，感觉还是太理论了，下面将通过特定场景介绍其使用： 1234567891011121314151617181920212223242526272829303132333435struct Goods&#123;	string _name;  // 名字	double _price; // 价格	int _evaluate; // 评价	Goods(const char* str, double price, int evaluate)		:_name(str)		, _price(price)		, _evaluate(evaluate)	&#123;&#125;&#125;;struct ComparePriceLess&#123;	bool operator()(const Goods&amp; gl, const Goods&amp; gr)	&#123;		return gl._price...</div></div></div></a><a class="pagination-related" href="/2025/05/26/CPP%E8%BF%9B%E9%98%B6/%E5%93%88%E5%B8%8C%E6%89%A9%E5%B1%95/" title="C++寻位映射的究极密码：哈希扩展"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250524151021.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="info text-right"><div class="info-1"><div class="info-item-1">下一篇</div><div class="info-item-2">C++寻位映射的究极密码：哈希扩展</div></div><div class="info-2"><div class="info-item-1">位图和布隆过滤器是基于哈希的一种常见应用，通常用来处理大体量数据，提升查找数据的效率 位图给40亿个不重复的无符号整数，没排过序。给一个无符号整数，如何快速判断一个数是否在这40亿个数中? 放在哈希表中去寻找？不，这并不现实，因为哈希表的存储也是需要空间消耗的，况且是 40 亿个数据，如此庞大的数据计算机一般是很难存储 因此就诞生了位图的概念，位图简单来说就是把每个数按照哈希函数的计算，存储到每个比特位上。数据是否在给定的整形数据中，结果是在或者不在，刚好是两种状态，那么可以使用一个二进制比特位来代表数据是否存在的信息，如果二进制比特位为 1，代表存在，为 0 代表不存在  位图的结构1234567891011template&lt;size_t N&gt;class bitset&#123;public:	bitset()	&#123;		_a.resize(N / 32 + 1);	&#125;private:	vector&lt;int&gt; _a;&#125;;  开辟一个 vector 数组 _a，这里我们以 int 作为位图的基本单位，那么就是把每个数据存储到...</div></div></div></a></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related" href="/2025/06/02/CPP%E8%BF%9B%E9%98%B6/C++11%EF%BC%88%E4%B8%8B%EF%BC%89/" title="C++日新月异的未来代码：C++11（下）"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250527175202.png" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-06-02</div><div class="info-item-2">C++日新月异的未来代码：C++11（下）</div></div><div class="info-2"><div class="info-item-1">接上篇，继续学习C++11的常用新特性 lambda表达式引入lambda 表达式是一种匿名函数对象，允许在代码中直接定义和使用小型的函数，无需额外定义函数或函数对象类，这么讲，感觉还是太理论了，下面将通过特定场景介绍其使用： 1234567891011121314151617181920212223242526272829303132333435struct Goods&#123;	string _name;  // 名字	double _price; // 价格	int _evaluate; // 评价	Goods(const char* str, double price, int evaluate)		:_name(str)		, _price(price)		, _evaluate(evaluate)	&#123;&#125;&#125;;struct ComparePriceLess&#123;	bool operator()(const Goods&amp; gl, const Goods&amp; gr)	&#123;		return gl._price...</div></div></div></a><a class="pagination-related" href="/2025/06/04/CPP%E8%BF%9B%E9%98%B6/%E6%99%BA%E8%83%BD%E6%8C%87%E9%92%88/" title="C++内存列传之RAII宇宙：智能指针"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250529155528.png" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-06-04</div><div class="info-item-2">C++内存列传之RAII宇宙：智能指针</div></div><div class="info-2"><div class="info-item-1">智能指针是 C++ 中用于自动管理动态内存的类模板，它通过 RAII（资源获取即初始化）技术避免手动 new &#x2F; delete 操作，从而显著减少内存泄漏和悬空指针的风险 为什么需要智能指针？123456789101112131415161718192021222324252627282930int div()&#123;	int a, b;	cin &gt;&gt; a &gt;&gt; b;	if (b == 0)		throw invalid_argument(&quot;除0错误&quot;);	return a / b;&#125;void Func()&#123;	int* p1 = new int;	int* p2 = new int;	cout &lt;&lt; div() &lt;&lt; endl;	delete p1;	delete p2;&#125;int main()&#123;	try	&#123;		Func();	&#125;	catch (exception&amp; e)	&#123;		cout &lt;&lt; e.what()...</div></div></div></a><a class="pagination-related" href="/2024/11/25/CPP%E5%88%9D%E9%98%B6/C++%E5%85%A5%E9%97%A8%EF%BC%88%E4%B8%8A%EF%BC%89/" title="C++命运石之门代码抉择：C++入门（上）"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20241125143913.jpg" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-11-25</div><div class="info-item-2">C++命运石之门代码抉择：C++入门（上）</div></div><div class="info-2"><div class="info-item-1">前言什么是C++  C++ 是一种高级编程语言，它在 C 语言的基础上发展而来的面向对象的语言，C++ 最初是由丹麦计算机科学家本贾尼・斯特劳斯特卢普（Bjarne Stroustrup）在 20 世纪 80 年代初期开发的，当时，C 语言已经在系统编程等领域广泛应用，但对于大型软件项目的开发，缺乏一些如代码复用、数据抽象等方便的机制，简单来说就是对一些自定义类型的完善，C++ 应运而生，它增加了类和对象等面向对象的概念，使得程序可以更好地组织和维护  C++的发展语言的开发都是在原先基础上增加新的语法规则，而不是删掉过去的语法规则，不然会导致以前编程环境下的代码都无法运行（python除外），于是在C语言的基础上进行扩展，增加了类的机制，称之为C with...</div></div></div></a><a class="pagination-related" href="/2024/11/27/CPP%E5%88%9D%E9%98%B6/C++%E5%85%A5%E9%97%A8%EF%BC%88%E4%B8%AD%EF%BC%89/" title="C++命运石之门代码抉择：C++入门（中）"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20241127125737.png" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-11-27</div><div class="info-item-2">C++命运石之门代码抉择：C++入门（中）</div></div><div class="info-2"><div class="info-item-1">C语言过渡到C++(中)函数重载是函数的一种特殊情况，C++允许在&#x3D;&#x3D;同一作用域&#x3D;&#x3D;中声明几个功能类似的同名函数，这些同名函数的形参列表不同在于参数个数 或 类型 或 类型顺序常用来处理实现功能类似数据类型不同的问题 函数重载的多种情况🚩参数类型不同 12345678910int Add(int left, int right)&#123;	 cout &lt;&lt; &quot;int Add(int left, int right)&quot; &lt;&lt; endl;	 return left + right;&#125;double Add(double left, double right)&#123;	 cout &lt;&lt; &quot;double Add(double left, double right)&quot; &lt;&lt; endl;	 return left + right;&#125; 一个函数类型为 int ，一个函数类型为 double...</div></div></div></a><a class="pagination-related" href="/2024/11/29/CPP%E5%88%9D%E9%98%B6/C++%E5%85%A5%E9%97%A8%EF%BC%88%E4%B8%8B%EF%BC%89/" title="C++命运石之门代码抉择：C++入门（下）"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20241129124329.jpg" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-11-29</div><div class="info-item-2">C++命运石之门代码抉择：C++入门（下）</div></div><div class="info-2"><div class="info-item-1">C语言过渡到C++(下)auto 关键字(C++11)为什么要用 auto？随着后续 C++ 语法的越来越深入，类型的长度可能会越来越长，因为在一些情境下是不允许把全部命名空间全部打开，所以在写类型时可能会遇到以下问题： • 类型难于拼写• 含义不明确导致容易出错 ⌨️比如后续学到迭代器有这么个类型 1std::map&lt;std::string, std::string&gt;::iterator 或许有聪明的人会想到直接用 typedef 给类型取别名不就好了，使用typedef给类型取别名确实可以简化代码，但是 typedef 有会遇到新的难题：  在编程时，常常需要把表达式的值赋值给变量，这就要求在声明变量的时候清楚地知道表达式的类型，然而有时候要做到这点并非那么容易，而且 typedef 只能定死变量的别名，auto 是自动推断的，因此 C++11 给 auto 赋予了新的含义  什么是 auto？早期的 auto：使用auto修饰的变量，是具有自动存储器的局部变量C++11 的新...</div></div></div></a><a class="pagination-related" href="/2025/02/19/CPP%E5%88%9D%E9%98%B6/list%E5%87%BD%E6%95%B0%E5%85%A8%E8%A7%A3/" title="C++效率掌握之STL库：list函数全解"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250218155357.jpg" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-02-19</div><div class="info-item-2">C++效率掌握之STL库：list函数全解</div></div><div class="info-2"><div class="info-item-1">为什么要学习list？什么是list？ list 是 C++ 标准模板库中的一个容器，它实现了双向链表的数据结构。双向链表由一系列节点组成，每个节点包含一个数据元素和两个指针，分别指向前一个节点和后一个节点。在链表的任意位置进行插入和删除操作的时间复杂度都是O(1) 。这使得它在需要频繁插入和删除元素的场景下表现出色，比如实现一个任务调度器，需要不断地添加新任务、移除已完成的任务  list 也是一种很常用的容器，对于链表的处理提供了极大的便利性  list 的主要特征可总结为：  list 是可以在常数范围内在任意位置进行插入和删除的序列式容器，并且该容器可以前后双向迭代 list 的底层是双向链表结构，双向链表中每个元素存储在互不相关的独立节点中，在节点中通过指针指向其前一个元素和后一个元素 list 与 forward_list 非常相似：最主要的不同在于 forward_list 是单链表，只能朝前迭代，已让其更简单高效 与其他的序列式容器相比(array，vector，deque)，list...</div></div></div></a></div></div><hr class="custom-hr"/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="card-info-avatar"><div class="avatar-img"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/zero_two.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-status-box"><div class="author-status"><g-emoji class="g-emoji" alias="palm_tree" fallback-src="https://lskypro.acozycotage.net/LightPicture/2022/12/fe1dc0402e623096.jpg">🤯</g-emoji><span>头脑风暴中</span></div></div></div><div class="author-info-name">澪贰</div><div class="author-info-description"></div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">96</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">74</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">9</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/ZeroCoder-Zhang"><i></i><span>🛫下一站--github</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/ZeroCoder-Zhang" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:1478943685@qq.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content"><center><b>--- 主域名 ---<br><a target="_blank" rel="noopener" href="https://general.zzh-blog.club/" title="主域名链接" class="anno_content"><font color="#5ea6e5">general.zzh-blog.club</font></a></b></center><center><b>--- 推广学习交流(Wechat) ---<br><a target="_blank" rel="noopener" href="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/微信扫码加好友.png" title="微信图片" class="anno_content"><font color="#5ea6e5">zzh1478943685(备注来意)</font></a></b></center></div><div id="welcome-info"></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BB%9F%E4%B8%80%E7%9A%84%E5%88%97%E8%A1%A8%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-number">1.</span> <span class="toc-text">统一的列表初始化</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%99%AE%E9%80%9A-%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-number">1.1.</span> <span class="toc-text">普通{ }初始化</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#initializer-list"><span class="toc-number">1.2.</span> <span class="toc-text">initializer_list</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%A3%B0%E6%98%8E"><span class="toc-number">2.</span> <span class="toc-text">声明</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#auto%E3%80%81nullptr"><span class="toc-number">2.1.</span> <span class="toc-text">auto、nullptr</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#decltype"><span class="toc-number">2.2.</span> <span class="toc-text">decltype</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%B7%A6%E5%80%BC%E5%8F%B3%E5%80%BC"><span class="toc-number">3.</span> <span class="toc-text">左值右值</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A6%82%E5%BF%B5"><span class="toc-number">3.1.</span> <span class="toc-text">概念</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B7%A6%E5%80%BC%E5%BC%95%E7%94%A8%E4%B8%8E%E5%8F%B3%E5%80%BC%E5%BC%95%E7%94%A8%E6%AF%94%E8%BE%83"><span class="toc-number">3.2.</span> <span class="toc-text">左值引用与右值引用比较</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B7%A6%E5%80%BC%E5%BC%95%E7%94%A8%E4%B8%8E%E5%8F%B3%E5%80%BC%E5%BC%95%E7%94%A8%E7%9A%84%E5%BA%94%E7%94%A8"><span class="toc-number">3.3.</span> <span class="toc-text">左值引用与右值引用的应用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%8C%E7%BE%8E%E8%BD%AC%E5%8F%91"><span class="toc-number">3.4.</span> <span class="toc-text">完美转发</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%B8%8C%E6%9C%9B%E8%AF%BB%E8%80%85%E4%BB%AC%E5%A4%9A%E5%A4%9A%E4%B8%89%E8%BF%9E%E6%94%AF%E6%8C%81"><span class="toc-number">4.</span> <span class="toc-text">希望读者们多多三连支持</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%B0%8F%E7%BC%96%E4%BC%9A%E7%BB%A7%E7%BB%AD%E6%9B%B4%E6%96%B0"><span class="toc-number">5.</span> <span class="toc-text">小编会继续更新</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BD%A0%E4%BB%AC%E7%9A%84%E9%BC%93%E5%8A%B1%E5%B0%B1%E6%98%AF%E6%88%91%E5%89%8D%E8%BF%9B%E7%9A%84%E5%8A%A8%E5%8A%9B%EF%BC%81"><span class="toc-number">6.</span> <span class="toc-text">你们的鼓励就是我前进的动力！</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2025/07/28/Linux/Linux%E7%8E%AF%E5%A2%83%E5%9F%BA%E7%A1%80%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7%E4%BD%BF%E7%94%A8/" title="【Linux操作系统】简学深悟启示录：Linux环境基础开发工具使用"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250728114434.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【Linux操作系统】简学深悟启示录：Linux环境基础开发工具使用"/></a><div class="content"><a class="title" href="/2025/07/28/Linux/Linux%E7%8E%AF%E5%A2%83%E5%9F%BA%E7%A1%80%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7%E4%BD%BF%E7%94%A8/" title="【Linux操作系统】简学深悟启示录：Linux环境基础开发工具使用">【Linux操作系统】简学深悟启示录：Linux环境基础开发工具使用</a><time datetime="2025-07-28T13:41:39.000Z" title="发表于 2025-07-28 21:41:39">2025-07-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2025/07/14/Linux/Linux%E6%9D%83%E9%99%90/" title="【Linux操作系统】简学深悟启示录：Linux权限"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250713233449.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【Linux操作系统】简学深悟启示录：Linux权限"/></a><div class="content"><a class="title" href="/2025/07/14/Linux/Linux%E6%9D%83%E9%99%90/" title="【Linux操作系统】简学深悟启示录：Linux权限">【Linux操作系统】简学深悟启示录：Linux权限</a><time datetime="2025-07-13T22:00:00.000Z" title="发表于 2025-07-14 06:00:00">2025-07-14</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2025/07/07/Linux/Linux%E5%9F%BA%E6%9C%AC%E6%8C%87%E4%BB%A4/" title="【Linux操作系统】简学深悟启示录：Linux基本指令"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250705182234.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【Linux操作系统】简学深悟启示录：Linux基本指令"/></a><div class="content"><a class="title" href="/2025/07/07/Linux/Linux%E5%9F%BA%E6%9C%AC%E6%8C%87%E4%BB%A4/" title="【Linux操作系统】简学深悟启示录：Linux基本指令">【Linux操作系统】简学深悟启示录：Linux基本指令</a><time datetime="2025-07-07T12:31:51.000Z" title="发表于 2025-07-07 20:31:51">2025-07-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2025/06/23/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/css%EF%BC%88%E4%B8%8B%EF%BC%89/" title="【前端基础】层叠宇宙的代码旅人：css（下）"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250608235413.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【前端基础】层叠宇宙的代码旅人：css（下）"/></a><div class="content"><a class="title" href="/2025/06/23/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/css%EF%BC%88%E4%B8%8B%EF%BC%89/" title="【前端基础】层叠宇宙的代码旅人：css（下）">【前端基础】层叠宇宙的代码旅人：css（下）</a><time datetime="2025-06-23T07:47:50.000Z" title="发表于 2025-06-23 15:47:50">2025-06-23</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2025/06/23/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/css%EF%BC%88%E4%B8%AD%EF%BC%89/" title="【前端基础】层叠宇宙的代码旅人：css（中）"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/909e58aa338befce9e0b2e4e683d50c.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【前端基础】层叠宇宙的代码旅人：css（中）"/></a><div class="content"><a class="title" href="/2025/06/23/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/css%EF%BC%88%E4%B8%AD%EF%BC%89/" title="【前端基础】层叠宇宙的代码旅人：css（中）">【前端基础】层叠宇宙的代码旅人：css（中）</a><time datetime="2025-06-23T07:44:20.000Z" title="发表于 2025-06-23 15:44:20">2025-06-23</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2024 - 2025 By 澪贰</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo 7.3.0</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly 5.3.5</a></div><div class="footer_custom_text">🏃‍➡️不是遇到同行伙伴再出发，而是出发后的路上遇到志同道合的人。<p></a>&nbsp;<a target="_blank" href="https://www.jsdelivr.com/"><img src= "" data-lazy-src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&logo=jsDelivr" title="本站使用JsDelivr为静态资源提供CDN加速"></a> &nbsp;<a target="_blank" href="https://vercel.com/ "><img src= "" data-lazy-src="https://img.shields.io/badge/Hosted-Vervel-brightgreen?style=flat&logo=Vercel" title="本站采用双线部署，默认线路托管于Vercel"></a>&nbsp;<a target="_blank" href="https://vercel.com/ "><img src= "" data-lazy-src="https://img.shields.io/badge/Hosted-Coding-0cedbe?style=flat&logo=Codio" title="本站采用双线部署，联通线路托管于Coding"></a>&nbsp;<a target="_blank" href="https://github.com/"><img src= "" data-lazy-src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&logo=GitHub" title="本站项目由Gtihub托管"></a>&nbsp;<a target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img src= "" data-lazy-src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&logo=Claris" title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可"></a></p></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="前往评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"><span id="percent">0</span><span>%</span></i></button><button id="go-down" type="button" title="直达底部" onclick="btf.scrollToDest(document.body.scrollHeight, 500)"><i class="fas fa-arrow-down"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"><script>(() => {
  const isShuoshuo = GLOBAL_CONFIG_SITE.pageType === 'shuoshuo'
  const option = null

  const getCount = () => {
    const countELement = document.getElementById('twikoo-count')
    if(!countELement) return
    twikoo.getCommentsCount({
      envId: 'https://twikoo.zzh-blog.club/',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(res => {
      countELement.textContent = res[0].count
    }).catch(err => {
      console.error(err)
    })
  }

  const init = (el = document, path = location.pathname) => {
    twikoo.init({
      el: el.querySelector('#twikoo-wrap'),
      envId: 'https://twikoo.zzh-blog.club/',
      region: '',
        placeholder: "|´・ω・)ノ嘿~都看到这儿了\n确定不评论一下再走嘛？\n(点完发送按钮等几秒哦~)",
        nicknamePlaceholder: "昵称/笔名",
        emailPlaceholder: "邮箱（不会公开）",
        urlPlaceholder: "个人站点",
      onCommentLoaded: () => {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)'))
      },
      ...option,
      path: isShuoshuo ? path : (option && option.path) || path
    })

    

    isShuoshuo && (window.shuoshuoComment.destroyTwikoo = () => {
      if (el.children.length) {
        el.innerHTML = ''
        el.classList.add('no-comment')
      }
    })
  }

  const loadTwikoo = (el, path) => {
    if (typeof twikoo === 'object') setTimeout(() => init(el, path), 0)
    else btf.getScript('https://cdn.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(() => init(el, path))
  }

  if (isShuoshuo) {
    'Twikoo' === 'Twikoo'
      ? window.shuoshuoComment = { loadComment: loadTwikoo }
      : window.loadOtherComment = loadTwikoo
    return
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = loadTwikoo
  }
})()</script></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script defer data-pjax src="/js/cat.js"></script><canvas id="universe"></canvas><script defer src="/js/universe.js"></script><script async src="/js/title.js"></script><script async src="//npm.elemecdn.com/pace-js@1.2.4/pace.min.js"></script><script defer data-pjax src="/js/readPercent.js"></script><div class="aplayer no-destroy" data-id="8459282733" data-server="netease" data-type="playlist" data-fixed="true" data-autoplay="true" data-listmaxheight=400px data-order="random"> </div><script src="https://cdn.staticfile.org/jquery/3.6.3/jquery.min.js"></script><script async data-pjax src="/js/txmap.js"></script><script src="source/js/统计图颜色适配.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="true"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script>(() => {
  const destroyAplayer = () => {
    if (window.aplayers) {
      for (let i = 0; i < window.aplayers.length; i++) {
        if (!window.aplayers[i].options.fixed) {
          window.aplayers[i].destroy()
        }
      }
    }
  }

  const runMetingJS = () => {
    typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()
  }

  btf.addGlobalFn('pjaxSend', destroyAplayer, 'destroyAplayer')
  btf.addGlobalFn('pjaxComplete', loadMeting, 'runMetingJS')
})()</script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>(() => {
  const pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

  window.pjax = new Pjax({
    elements: 'a:not([target="_blank"])',
    selectors: pjaxSelectors,
    cacheBust: false,
    analytics: false,
    scrollRestoration: false
  })

  const triggerPjaxFn = (val) => {
    if (!val) return
    Object.values(val).forEach(fn => fn())
  }

  document.addEventListener('pjax:send', () => {
    // removeEventListener
    btf.removeGlobalFnEvent('pjaxSendOnce')
    btf.removeGlobalFnEvent('themeChange')

    // reset readmode
    const $bodyClassList = document.body.classList
    if ($bodyClassList.contains('read-mode')) $bodyClassList.remove('read-mode')

    triggerPjaxFn(window.globalFn.pjaxSend)
  })

  document.addEventListener('pjax:complete', () => {
    btf.removeGlobalFnEvent('pjaxCompleteOnce')
    document.querySelectorAll('script[data-pjax]').forEach(item => {
      const newScript = document.createElement('script')
      const content = item.text || item.textContent || item.innerHTML || ""
      Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
      newScript.appendChild(document.createTextNode(content))
      item.parentNode.replaceChild(newScript, item)
    })

    triggerPjaxFn(window.globalFn.pjaxComplete)
  })

  document.addEventListener('pjax:error', e => {
    if (e.request.status === 404) {
      const usePjax = true
      true 
        ? (usePjax ? pjax.loadUrl('/404.html') : window.location.href = '/404.html')
        : window.location.href = e.request.responseURL
    }
  })
})()</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="text-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="输入你想搜索的关键字" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div><!-- hexo injector body_end start --><script data-pjax>
    function butterfly_categories_card_injector_config(){
      var parent_div_git = document.getElementById('recent-posts');
      var item_html = '<style>li.categoryBar-list-item{width:24%;}.categoryBar-list{max-height: 380px;overflow:auto;}.categoryBar-list::-webkit-scrollbar{width:0!important}@media screen and (max-width: 650px){.categoryBar-list{max-height: 320px;}}</style><div class="recent-post-item" style="height:auto;width:100%;padding:0px;"><div id="categoryBar"><ul class="categoryBar-list"><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163139.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/Linux/&quot;);" href="javascript:void(0);">Linux</a><span class="categoryBar-list-count">3</span><span class="categoryBar-list-descr">C++笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163140.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/C-初阶/&quot;);" href="javascript:void(0);">C++初阶</a><span class="categoryBar-list-count">19</span><span class="categoryBar-list-descr">C语言笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_202507101631401.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/C语言/&quot;);" href="javascript:void(0);">C语言</a><span class="categoryBar-list-count">22</span><span class="categoryBar-list-descr">Linux笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163130.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/Microi吾码/&quot;);" href="javascript:void(0);">Microi吾码</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr">C++笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163135.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/C-进阶/&quot;);" href="javascript:void(0);">C++进阶</a><span class="categoryBar-list-count">19</span><span class="categoryBar-list-descr">低代码</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163137.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/优选算法/&quot;);" href="javascript:void(0);">优选算法</a><span class="categoryBar-list-count">11</span><span class="categoryBar-list-descr">数据结构笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163136.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/前端基础/&quot;);" href="javascript:void(0);">前端基础</a><span class="categoryBar-list-count">5</span><span class="categoryBar-list-descr">入门常用算法</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163132.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/话题/&quot;);" href="javascript:void(0);">话题</a><span class="categoryBar-list-count">5</span><span class="categoryBar-list-descr">前端基础笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163134.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/初阶数据结构/&quot;);" href="javascript:void(0);">初阶数据结构</a><span class="categoryBar-list-count">10</span><span class="categoryBar-list-descr">杂谈</span></li></ul></div></div>';
      console.log('已挂载butterfly_categories_card')
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      }
    if( document.getElementById('recent-posts') && (location.pathname ==='/'|| '/' ==='all')){
    butterfly_categories_card_injector_config()
    }
  </script><script data-pjax>
  function butterfly_footer_beautify_injector_config(){
    var parent_div_git = document.getElementById('footer-wrap');
    var item_html = '<div id="workboard"></div><p id="ghbdages"><a class="github-badge" target="_blank" href="https://hexo.io/" style="margin-inline:5px" data-title="博客框架为Hexo" title=""><img src= "" data-lazy-src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&amp;logo=hexo" alt=""/></a><a class="github-badge" target="_blank" href="https://butterfly.js.org/" style="margin-inline:5px" data-title="主题使用Butterfly" title=""><img src= "" data-lazy-src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&amp;logo=bitdefender" alt=""/></a></p>';
    console.log('已挂载butterfly_footer_beautify')
    parent_div_git.insertAdjacentHTML("beforeend",item_html)
    }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_footer_beautify_injector_config();
  }
  else if (epage === cpage){
    butterfly_footer_beautify_injector_config();
  }
  </script><script async src="https://unpkg.zhimg.com/hexo-butterfly-footer-beautify@1.0.0/lib/runtime.min.js"></script><script data-pjax>
  function butterfly_swiper_injector_config(){
    var parent_div_git = document.getElementById('recent-posts');
    var item_html = '<div class="recent-post-item" style="height: auto;width: 100%"><div class="blog-slider swiper-container-fade swiper-container-horizontal" id="swiper_container"><div class="blog-slider__wrp swiper-wrapper" style="transition-duration: 0ms;"><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/02/28/话题/DeepSeek、Grok 和 ChatGPT 对比分析/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/77c5921463a44f418828ae47de6671e5.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-02-28</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/02/28/话题/DeepSeek、Grok 和 ChatGPT 对比分析/&quot;);" href="javascript:void(0);" alt="">DeepSeek、Grok 和 ChatGPT 对比分析：从技术与应用场景的角度深入探讨</a><div class="blog-slider__text">在人工智能领域，随着技术的快速发展，不同的工具和框架不断涌现，为开发者提供了更多选择。DeepSeek、Grok 和 ChatGPT 作为三款备受关注的工具，每一款都有其独特的优势和适用场景。本文将从技术特点、应用场景以及实际案例分析的角度，对这三款工具进行对比，帮助读者更好地理解它们的区别和适用场景</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/02/28/话题/DeepSeek、Grok 和 ChatGPT 对比分析/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/02/20/话题/C++方向后端开发学习指南/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/44fa280c73e53024f749363207753e1.png" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-02-20</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/02/20/话题/C++方向后端开发学习指南/&quot;);" href="javascript:void(0);" alt="">当前就业形势下C++方向后端开发学习指南</a><div class="blog-slider__text">在信息技术飞速发展的今天，后端开发成为了软件开发领域中极其重要的组成部分。对于很多程序员来说，C++仍然是一个强大且广泛应用的编程语言，尤其在后端开发中有着不可忽视的地位。本文将深入探讨C++方向后端开发的学习路线，分析当前就业形势下的职业方向选择，并结合图示和代码示例，帮助读者系统化地学习C++后端开发</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/02/20/话题/C++方向后端开发学习指南/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/02/20/话题/AIGC训练效率/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/419f4f95b11526f92f62fe38778d0a9.png" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-02-20</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/02/20/话题/AIGC训练效率/&quot;);" href="javascript:void(0);" alt="">AIGC训练效率与模型优化的深入探讨</a><div class="blog-slider__text">人工智能领域的发展，人工智能生成内容（ [AIGC](https://aigc.izzi.cn/)）越来越受关注。AIGC能够通过学习大量数据生成高质量内容，但训练效率和模型优化仍然是关键的研究方向。本博客将深入探AIGC的训练效率，与模型优化的相关策略和技术，提供相应代码示例和图示，以帮助读者更好地理解该领域</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/02/20/话题/AIGC训练效率/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/02/28/话题/如何高效利用DeepSeek/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/e640e59c2f92482993b52c845adf7844.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-02-28</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/02/28/话题/如何高效利用DeepSeek/&quot;);" href="javascript:void(0);" alt="">如何高效利用DeepSeek：深入探索AI搜索引擎的潜力</a><div class="blog-slider__text">随着人工智能技术的飞速发展，传统的搜索引擎正逐步向更智能化、个性化的方向演进。作为一款基于深度学习的AI搜索引擎，DeepSeek（深度求索）不仅在理解用户意图方面展现出色，还通过集成丰富的知识图谱和提供多样化的信息类型，成为现代用户的信息获取利器。本文将详细分析如何高效利用DeepSeek，探讨其核心技术、实际应用场景以及性能优化方法</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/02/28/话题/如何高效利用DeepSeek/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/01/31/话题/本地部署Deepseek/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/2373381f0feae7cd4964af546e9e462.png" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-01-31</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/01/31/话题/本地部署Deepseek/&quot;);" href="javascript:void(0);" alt="">如何快速高效本地部署DeepseekR1大模型？保姆级教程 无惧隐私威胁</a><div class="blog-slider__text">DeepSeek 隐私政策中提到了关于用户输入信息收集的条款，无论你输入什么文本，以及上传什么文件都会被第三方机构所收集，所以如果是在进行相关的项目研究或者实验进展分析的时候，就很有必要对数据进行隐私保护，且本地部署是支持离线的</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/01/31/话题/本地部署Deepseek/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div></div><div class="blog-slider__pagination swiper-pagination-clickable swiper-pagination-bullets"></div></div></div>';
    console.log('已挂载butterfly_swiper')
    parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  var elist = 'undefined'.split(',');
  var cpage = location.pathname;
  var epage = '/';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_swiper_injector_config();
  }
  else if (epage === cpage){
    butterfly_swiper_injector_config();
  }
  </script><script defer src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.js"></script><script defer data-pjax src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper_init.js"></script><script data-pjax src="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.js"></script><script data-pjax>
  function gitcalendar_injector_config(){
      var parent_div_git = document.getElementById('gitZone');
      var item_html = '<div class="recent-post-item" id="gitcalendarBar" style="width:100%;height:auto;padding:10px;"><style>#git_container{min-height: 280px}@media screen and (max-width:650px) {#git_container{min-height: 0px}}</style><div id="git_loading" style="width:10%;height:100%;margin:0 auto;display: block;"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50" xml:space="preserve"><path fill="#d0d0d0" d="M25.251,6.461c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615V6.461z" transform="rotate(275.098 25 25)"><animatetransform attributeType="xml" attributeName="transform" type="rotate" from="0 25 25" to="360 25 25" dur="0.6s" repeatCount="indefinite"></animatetransform></path></svg><style>#git_container{display: none;}</style></div><div id="git_container"></div></div>';
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      console.log('已挂载gitcalendar')
      }

    if( document.getElementById('gitZone') && (location.pathname ==='/about/'|| '/about/' ==='all')){
        gitcalendar_injector_config()
        GitCalendarInit("https://gitcalendar.zzh-blog.club/api?ZeroCoder-Zhang",['#d9e0df', '#c6e0dc', '#a8dcd4', '#9adcd2', '#89ded1', '#77e0d0', '#5fdecb', '#47dcc6', '#39dcc3', '#1fdabe', '#00dab9'],'ZeroCoder-Zhang')
    }
  </script><div class="js-pjax"><script async="async">var arr = document.getElementsByClassName('recent-post-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '2s');
    arr[i].setAttribute('data-wow-delay', '1s');
    arr[i].setAttribute('data-wow-offset', '100');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script><script async="async">var arr = document.getElementsByClassName('card-widget');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '');
    arr[i].setAttribute('data-wow-delay', '');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script></div><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow.min.js"></script><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow_init.js"></script><!-- hexo injector body_end end --><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/koharu.model.json"},"display":{"position":"right","hOffset":40,"vOffset":0,"width":150,"height":300},"mobile":{"show":false},"log":false});</script></body></html>